import { Table } from 'antd';
import React, { useEffect, useState } from 'react';
import PermissionModal from './Permission';

const MOTable = props => {

    const { dispatch, className, data, isMobile, MOtableCols} = props;
    const [selectedRowKeys, setSelectedRowKeys] = useState([]);
    const [modalVisible, setModalVisible] = useState(false);
    const [permObject, setPermObject] = useState(null);

    const TODetail = (event, item, record) => {
        const { type, payload } = item.canClick;
        event.preventDefault();
        if (payload) { payload.record = record }
        dispatch({ type, payload: payload });
    }

    const MOcolumns = () => {
        const columns = [];
        const renderTh = (item, i) => {
            const th = {
                key: i, title: item.text, dataIndex: item.dataIndex, ellipsis: true, width: item.width,
                render: item.render || ''
            }
            if (item.canClick) {

                th.render = (field, record) => (
                    <a href="#" onClick={(event) => TODetail(event, item, record)}>
                        {item.render ? item.render(field, record) : field}
                    </a>
                );
            }
            if (item.hasModal) {
                th.render = (field, record) => item.render(setModalVisible, setPermObject)
            }

            return th
        }

        MOtableCols 
        && MOtableCols.forEach((item, i) => {
            if (isMobile) {
                !item.isHidden
                && columns.push(renderTh(item, i));
            }
            else {
                columns.push(renderTh(item, i));
            }
        })

        return columns;
    };

    const rowSelection = {

        selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => { // _:占位符
            // console.log(`selectedRows:`, selectedRows, selectedRowKeys, checkedRows);
            setSelectedRowKeys(selectedRowKeys);
            selectedRows instanceof Array
            && dispatch({
                type: 'manager/updateCheckedRows',
                payload: selectedRows
            })
        },
    }
    
    useEffect(() =>{
        console.log('===.>> MOTable is run!')
        dispatch && dispatch({ type: 'manager/methodAdapter', method: 'query', payload: {} })
    }, [])

    useEffect(() => {
        // console.log('==>> data is change!', data)
        setSelectedRowKeys([]);
    }, [data])

    return (
        <>
            <Table
                className={className}
                rowSelection={rowSelection}
                columns={MOcolumns()}
                dataSource={data}
            />
            <PermissionModal 
                modalVisible={modalVisible}
                onCancle={() => {setModalVisible(false);}}
                permObject={permObject}
            />
        </>
    );
}

export default MOTable;